package utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.getTimer;
	
	import worlds.BaseWorld;

	public class EnterFrameTimer extends EventDispatcher
	{
		private var _delay					: Number;
		private var _repeatCount			: int;
		private var _currentCount			: int = 0;
		private var _running				: Boolean = false;
		
		private var _lastTick				: int;// 记录上一次getTimer()的值
		
		/**
		 * 
		 * 获取或设置计时器事件间的延迟（以毫秒为单位）。
		 * 
		 */		
		public function get delay():Number {
			return _delay;
		}
		public function set delay(value:Number):void {
			_delay = value;
		}
		/**
		 * 
		 * 获取或设置计时器运行总次数。
		 * 
		 */		
		public function get repeatCount():int {
			return _repeatCount;
		}
		public function set repeatCount(value:int):void {
			_repeatCount = value;
		}
		/**
		 * 
		 * 获取计时器从 0 开始后触发的总次数。
		 * 
		 */		
		public function get currentCount():int {
			return _currentCount;
		}
		/**
		 * 
		 * 获取计时器的当前状态；如果计时器正在运行，则为 true，否则为 false。
		 * 
		 */		
		public function get running():Boolean {
			return _running;
		}
		
		public function EnterFrameTimer(delay:Number, repeatCount:int = 0)
		{
			super();
			_delay = delay;
			_repeatCount = repeatCount
			init();
		}
		private function init():void {
			BaseWorld.getInstance().addEventListener(Event.ENTER_FRAME, enterFrameHandler);
		}
		private function enterFrameHandler(event:Event):void {
			if(!_running) return;
			var tick:int = getTimer();
			while(tick - _lastTick >= _delay) {
				dispatchEvent(new TimerEvent(TimerEvent.TIMER));
				_lastTick += _delay;
				if(_repeatCount > 0 && (++ _currentCount) >= _repeatCount) {
					dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
					_running = false;
					break;
				}
			}
		}
		
		/**
		 *
		 * 如果计时器尚未运行，则启动计时器。 
		 * 
		 */		
		public function start():void {
			if(_repeatCount <= 0 || _currentCount < _repeatCount) {
				_running = true;
				_lastTick = getTimer();
			}
		}
		/**
		 *
		 * 停止计时器。 
		 * 
		 */	
		public function stop():void {
			_running = false;
		}
		/**
		 *
		 * 如果计时器正在运行，则停止计时器，并将 currentCount 属性设回为 0，这类似于秒表的重置按钮。 
		 * 
		 */		
		public function reset():void {
			_running = false;
			_currentCount = 0;
		}
	}
}